import React from 'react'
import {Link, routerRedux} from 'dva/router';
import {Layout, Menu, Icon, Dropdown, Avatar, Tag, Spin, message} from 'antd';
// import HeaderSearch from '../../components/HeaderSearch/index';
// import NoticeIcon from '../../components/NoticeIcon/index';
import moment from 'moment';
import groupBy from 'lodash/groupBy';
import CSetting from './CSetting';
import styles from './CHeader.less'
import {defaultAvatar} from '../../config/config';

const {Header} = Layout;
const {Item, Divider} = Menu;

export default class CHeader extends React.PureComponent {

  toggleSider = () => {
    this.props.dispatch({
      type: 'global/switchCollapsed',
    });
  };

  handleNoticeClear = (type) => {
    message.success(`清空了${type}`);
    this.props.dispatch({
      type: 'global/clearNotices',
      payload: type,
    });
  };

  handleNoticeVisibleChange = (visible) => {
    if (visible) {
      this.props.dispatch({
        type: 'global/fetchNotices',
      });
    }
  };

  getNoticeData() {
    const {notices = []} = this.props;
    if (notices.length === 0) {
      return {};
    }
    const newNotices = notices.map(item => {
      const newNotice = {...item};
      if (newNotice.datetime) {
        newNotice.datetime = moment(item.datetime).fromNow();
      }
      // transform id to item key
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      if (newNotice.extra && newNotice.status) {
        const color = ({
          todo: '',
          processing: 'blue',
          urgent: 'red',
          doing: 'gold',
        })[newNotice.status];
        newNotice.extra = <Tag color={color} style={{marginRight: 0}}>{newNotice.extra}</Tag>;
      }
      return newNotice;
    });
    return groupBy(newNotices, 'type');
  }

  handleMenuClick = ({key}) => {
    switch (key) {
      case 'center':
        this.props.dispatch(routerRedux.push(`/user/${this.props.currentUser.id}`));
        break;
      case 'setting':
        this.props.dispatch({
          type: 'global/showSettingModal',
        });
        break;
      case 'logout':
        this.props.dispatch({
          type: 'user/logout',
        });
        break;
      default:
        break;
    }
  };

  render() {
    const {dispatch, currentUser = {}, lightTheme, collapsed, notifyCount, fetchingNotices, settingModalVisable} = this.props;
    const noticeData = this.getNoticeData();
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        <Item key="center"><Icon type="user"/>个人中心</Item>
        <Item key="setting"><Icon type="desktop"/>界面设置</Item>
        <Divider/>
        <Item key="logout"><Icon type="logout"/>退出登录</Item>
      </Menu>
    );
    const settingProps = {
      dispatch,
      lightTheme,
      collapsed,
      settingModalVisable,
      toggleSider: this.toggleSider,
    };

    return (
      <Header className={styles.header}>
        <Icon
          className={styles.trigger}
          type={collapsed ? 'menu-unfold' : 'menu-fold'}
          onClick={this.toggleSider}
        />
        <div className={styles.right}>
          {/*<HeaderSearch
            className={`${styles.action} ${styles.search}`}
            placeholder="站内搜索"
            dataSource={['搜索提示一', '搜索提示二', '搜索提示三']}
            onSearch={(value) => {
              console.log('input', value); // eslint-disable-line
            }}
            onPressEnter={(value) => {
              console.log('enter', value); // eslint-disable-line
            }}
          />
          <NoticeIcon
            className={styles.action}
            count={notifyCount}
            onItemClick={(item, tabProps) => {
              console.log(item, tabProps); // eslint-disable-line
            }}
            onClear={this.handleNoticeClear}
            onPopupVisibleChange={this.handleNoticeVisibleChange}
            loading={fetchingNotices}
            popupAlign={{offset: [20, -16]}}
          >
            <NoticeIcon.Tab
              list={noticeData['通知']}
              title="通知"
              emptyText="你已查看所有通知"
              emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
            />
            <NoticeIcon.Tab
              list={noticeData['消息']}
              title="消息"
              emptyText="您已读完所有消息"
              emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg"
            />
            <NoticeIcon.Tab
              list={noticeData['待办']}
              title="待办"
              emptyText="你已完成所有待办"
              emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg"
            />
          </NoticeIcon>*/}
          {currentUser.name
            ? <Dropdown overlay={menu}>
							<span className={`${styles.action} ${styles.account}`}>
								<Avatar size="small" className={styles.avatar} src={currentUser.avatar || defaultAvatar}/>
                {currentUser.name}
							</span>
            </Dropdown>
            : <Spin size="small" style={{marginLeft: 8}}/>}
        </div>
        <CSetting {...settingProps} />
      </Header>
    );
  }
}
